package com.judian.smart.util;

import android.text.TextUtils;

import com.judian.smart.base.MyApplication;
import com.judian.smart.model.SongPlayInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class SongUitils {
    public static List<SongPlayInfo> list = new ArrayList<SongPlayInfo>();
    private static File jsonFile = new File(MyApplication.getInstance()
            .getRootPath() + File.separator + "song_json");

    static {
        if (list.size() == 0) {
            String json = JSONFileUtils.getJsonStringFromFile(jsonFile)
                    .replace("\r\n", "");
            if (!TextUtils.isEmpty(json)) {
                try {
                    list = (List<SongPlayInfo>) JSONHelper.parseCollection(json,
                            List.class, SongPlayInfo.class);

                } catch (Exception e) {
                    // TODO: handle exceptionus
                }
            }
        }
    }

    public static int add(SongPlayInfo _songPlayInfo) {
        int result = 0;
        for (int i = 0; i < list.size(); i++) {
            SongPlayInfo songPlayInfo = list.get(i);
            if (songPlayInfo.getSongName().equals(_songPlayInfo.getSongName())) {
                result = 1;
                break;
            }
        }
        if (result == 0) {
            list.add(_songPlayInfo);
            save();
        }
        return result;
    }

    //删除当前歌曲
    public static void delete(SongPlayInfo _songPlayInfo) {
        for (int i = 0; i < list.size(); i++) {
            SongPlayInfo songPlayInfo = list.get(i);
            if (songPlayInfo.getSongName().equals(_songPlayInfo.getSongName())) {
                list.remove(songPlayInfo);
                save();
                break;
            }
        }
    }

    public static void deleteAll() {
        list.clear();
        save();
    }

    public static void save() {
        try {
            String json = JSONHelper.toJSON(list);
            JSONFileUtils.saveJSONToFile(jsonFile, json);
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }


}
